package com.tianruan.dc.common.user;

import com.tianruan.dc.common.auth.MAuthenticationUser;
import com.tianruan.dc.modules.sys.user.entity.db.PermissionDO;
import com.tianruan.dc.modules.sys.user.entity.dto.UserDTO;
import com.tianruan.dc.modules.sys.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @PS 用户详细信息
 */
@Component
public class MUserDetailService implements UserDetailsService {

    @Autowired
    private IUserService userService;


    /**
     * 根据用户名登录
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDTO user = userService.getUserPermissionByNo(username);

        if (user == null) {
            throw new UsernameNotFoundException("用户没找到");
        } else if("0".equals(user.getLoginFlag())) {
            throw new UsernameNotFoundException("用户已被锁定");
        }

        String[] permissionList = user.getPermissionList().stream().map(PermissionDO::getPermission).toArray(String[]::new);
        return new MAuthenticationUser(user.getId(), user.getOfficeId(), user.getName(),
                user.getUsername(),
                user.getPassword(),
                user.getNo(),
                user.getPhone(),
                user.getEmail(),
                user.getSex(),
                AuthorityUtils.createAuthorityList(permissionList));
    }


}
